package com.sky.zzh.home;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.next.intf.ITaskListener;
import com.next.net.SHGet;
import com.next.net.SHTask;
import com.sky.widget.sweetdialog.SweetDialog;
import com.sky.widget.sweetdialog.SweetDialog.OnSweetClickListener;
import com.sky.zzh.BaseFragActivity;
import com.sky.zzh.R;
import com.sky.zzh.SHApplication;
import com.sky.zzh.SHContainerActivity;
import com.sky.zzh.analyse.AnalyseFragment;
import com.sky.zzh.devicemanager.DeviceManagerFragment;
import com.sky.zzh.setting.SelfInfoFragment;
import com.sky.zzh.setting.SettingFragment;
import com.sky.zzh.sleepset.SleepSetFragment;
import com.sky.zzh.today.TodayDataFragment;
import com.sky.zzh.util.AsyncTaskImageLoad;
import com.sky.zzh.util.CommonUtil;
import com.sky.zzh.util.ConfigDefinition;
import com.sky.zzh.util.UserInfoManager;
import com.sky.zzh.view.CircularImage;
import com.sky.zzh.view.SlidingMenu;

public class ZZHMainActivity extends BaseFragActivity implements ITaskListener {

	private int count = 0;
	private SlidingMenu mLeftMenu;
	private List<Fragment> mFragmentList = new ArrayList<Fragment>();
	private String[] tabs = new String[] { "today", "analyse", "device", "sleepset", "setting" };
	private RelativeLayout[] mRl = new RelativeLayout[5];
	// private TextView mTvTitle;
	// private Button mBtnRight;
	private LinearLayout mLlMain, mLlInfo;
	private TextView mTvName;
	private SHGet infoTask,sensorInfoTask;
	private CircularImage mIvHead;
	//play sound
	private SoundPool pool;  
	private int sourceid;
	private boolean canPlay;
	private BroadcastReceiver rec = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			if("name_change".equals(arg1.getAction())){
				mTvName.setText(UserInfoManager.getInstance().getUsername());
//				LoadImage(mIvHead, ConfigDefinition.URL + "file/DownloadFile/" + UserInfoManager.getInstance().getUserId());
				LoadImage(mIvHead,ConfigDefinition.photourl);
			}else{
				changeFragment(tabs[2]);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		registerBroadcast();
		mLeftMenu = (SlidingMenu) findViewById(R.id.id_menu);
		// mTvTitle = (TextView) findViewById(R.id.tv_title);
		// mBtnRight = (Button) findViewById(R.id.btn_right);
		mLlMain = (LinearLayout) findViewById(R.id.ll_main);
		mLlInfo = (LinearLayout) findViewById(R.id.ll_info);
		mRl[0] = (RelativeLayout) findViewById(R.id.rl_0);
		mRl[1] = (RelativeLayout) findViewById(R.id.rl_1);
		mRl[2] = (RelativeLayout) findViewById(R.id.rl_2);
		mRl[3] = (RelativeLayout) findViewById(R.id.rl_3);
		mRl[4] = (RelativeLayout) findViewById(R.id.rl_4);
		mTvName = (TextView) findViewById(R.id.tv_name);
		mIvHead = (CircularImage) findViewById(R.id.iv_photo);

//		if (!CommonUtil.isEmpty(UserInfoManager.getInstance().getUsername())  && !"normal".equals(ConfigDefinition.LoginType)) {
//			mTvName.setText(UserInfoManager.getInstance().getUsername());
//		} else {
//			requestInfo();
//		}

		setListeners();
		changeFragment(tabs[0]);

		if("qq".equals(UserInfoManager.getInstance().getLoginType())){
			LoadImage(mIvHead, UserInfoManager.getInstance().getPhotoQQ());
			mTvName.setText(UserInfoManager.getInstance().getNickQQ());
		}else if("sina".equals(UserInfoManager.getInstance().getLoginType())){
			LoadImage(mIvHead, UserInfoManager.getInstance().getPhotoSina());
			mTvName.setText(UserInfoManager.getInstance().getNickSina());
		}else if("weixin".equals(UserInfoManager.getInstance().getLoginType())){
			LoadImage(mIvHead, UserInfoManager.getInstance().getPhotoWeixin());
			mTvName.setText(UserInfoManager.getInstance().getNickWeixin());
		}else{
			LoadImage(mIvHead, ConfigDefinition.photourl);
			requestInfo();
		}
		
		Timer timer=new Timer();//实例化一个定时器
		final Handler handler=new Handler(){//实例化一个Handler，并复写handlerMessage方法
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {//这句就不做说明了，都能看懂
				case 1:
					//实例化时一个TimerTask实力类，调用构造函数，并执行run方法，测试用，看方法是否定时执行
					requestSensorInfo();
					break;
				}
				super.handleMessage(msg);
			}
			
		};
		
		initPool();
		playSound();
		TimerTask timerTask=new TimerTask() {//实例TimerTask,在run函数中向hangdler发送消息
			
			@Override
			public void run() {
				Message message=new Message();
				message.what=1;
				handler.sendMessage(message);
			}
		};
		timer.schedule(timerTask,0,5000);
	}

	private void initPool(){
		//指定声音池的最大音频流数目为10，声音品质为5  
        pool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);  
        //载入音频流，返回在池中的id  
        sourceid = pool.load(this, R.raw.noti, 0);  
        pool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
            
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                     // TODO Auto-generated method stub
                     canPlay = true;
//                     playSound();//测试是否可以播放
                    }
      });
	}
	
	private void requestSensorInfo(){
		sensorInfoTask = new SHGet();
		sensorInfoTask.setUrl(ConfigDefinition.URL + "app/SensorInfo");
		sensorInfoTask.setListener(this);
		sensorInfoTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
		sensorInfoTask.start();
	}
	
	private void requestInfo() {
		infoTask = new SHGet();
		infoTask.setUrl(ConfigDefinition.URL + "user/UserInfo");
		infoTask.setListener(this);
		infoTask.getTaskArgs().put("UserID", UserInfoManager.getInstance().getUserId());
		infoTask.start();
	}

	private void registerBroadcast() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("name_change");
		intentFilter.addAction("addDevice");
		registerReceiver(rec, intentFilter);
	}

	public void toggleMenu(View view) {
		mLeftMenu.toggle();
	}

	private void setListeners() {
		mRl[0].setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				changeFragment(tabs[0]);
				// mTvTitle.setText("今日数据");
				mLeftMenu.toggle();
				// mBtnRight.setVisibility(View.GONE);
				// mLlMain.setBackgroundResource(R.drawable.img_bg_night);
			}
		});

		mRl[1].setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				changeFragment(tabs[1]);
				// mTvTitle.setText("睡眠分析");
				mLeftMenu.toggle();
				// mBtnRight.setVisibility(View.VISIBLE);
				// mLlMain.setBackgroundResource(R.drawable.img_bg);
			}
		});

		mRl[2].setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				changeFragment(tabs[2]);
				// mTvTitle.setText("设备管理");
				mLeftMenu.toggle();
				// mBtnRight.setVisibility(View.GONE);
			}
		});

		mRl[3].setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				changeFragment(tabs[3]);
				// mTvTitle.setText("睡眠设置");
				mLeftMenu.toggle();
				// mBtnRight.setVisibility(View.GONE);
			}
		});

		mRl[4].setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				changeFragment(tabs[4]);
				// mTvTitle.setText("设定");
				mLeftMenu.toggle();
				// mBtnRight.setVisibility(View.GONE);
			}
		});

		mLlInfo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ZZHMainActivity.this, SHContainerActivity.class);
				intent.putExtra("class", SelfInfoFragment.class.getName());
				startActivity(intent);
			}
		});
	}

	/**
	 * 切换界面
	 * 
	 * @param tag
	 */
	public void changeFragment(String tag) {
		hideFragment();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
		if (fragment != null) {
			transaction.show(fragment);
		} else {
			if (tag.equals(tabs[0])) {

				fragment = new TodayDataFragment();

			} else if (tag.equals(tabs[1])) {
				fragment = new AnalyseFragment();
			} else if (tag.equals(tabs[2])) {
				fragment = new DeviceManagerFragment();
			} else if (tag.equals(tabs[3])) {
				fragment = new SleepSetFragment();
			} else if (tag.equals(tabs[4])) {
				fragment = new SettingFragment();
			}
			mFragmentList.add(fragment);
			transaction.add(R.id.frame, fragment, tag);
		}
		transaction.commit();

	}

	private void hideFragment() {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		for (Fragment f : mFragmentList) {
			ft.hide(f);
		}
		ft.commit();
	}

	@Override
	public void onTaskFinished(SHTask task) throws Exception {
		// TODO Auto-generated method stub
		JSONObject json = new JSONObject(task.getResult().toString());
		if (task == infoTask) {
			if ("200".equals(json.optString("ReturnCode"))) {
				JSONObject infoJson = json.optJSONObject("UserInfo");
				UserInfoManager.getInstance().setUsername(infoJson.optString("UserName"));
				if(!CommonUtil.isEmpty(infoJson.optString("SleepStartTime"))){
					UserInfoManager.getInstance().setStartTime(infoJson.optString("SleepStartTime"));
				}
				if(!CommonUtil.isEmpty(infoJson.optString("SleepEndTime"))){
					UserInfoManager.getInstance().setEndTime(infoJson.optString("SleepEndTime"));
				}
				
				String min = infoJson.optString("AlarmTimeOutOfBed");
				System.out.println("AlarmTimeOutOfBed+"+min);
				if("0.08".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(5);
					UserInfoManager.getInstance().setLichuang("5秒");
				}else if("0.25".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(15);
					UserInfoManager.getInstance().setLichuang("15秒");
				}else if("0.5".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(30);
					UserInfoManager.getInstance().setLichuang("30秒");
				}else if("1".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(60);
					UserInfoManager.getInstance().setLichuang("1分钟");
				}else if("5".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(300);
					UserInfoManager.getInstance().setLichuang("5分钟");
				}else if("10".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(600);
					UserInfoManager.getInstance().setLichuang("10分钟");
				}else if("15".equals(min)){
					UserInfoManager.getInstance().setLichuangTime(900);
					UserInfoManager.getInstance().setLichuang("15分钟");
				}
				if(!"0".equals(infoJson.optString("AlarmTimeSleepTooLong"))){
					System.out.println("-----"+infoJson.optString("AlarmTimeSleepTooLong"));
					String temp[] = infoJson.optString("AlarmTimeSleepTooLong").split(".");
					if(temp.length == 2){
						UserInfoManager.getInstance().setJiushui(temp[0]+":"+Integer.valueOf(temp[1])*60/100);
					}else{
						UserInfoManager.getInstance().setJiushui(temp[0]+":"+"00");
					}
				}
				UserInfoManager.getInstance().sync(this, true);
				mTvName.setText(infoJson.optString("UserName"));
			}
		}else if(task == sensorInfoTask){
			if ("200".equals(json.optString("ReturnCode"))) {
				JSONObject infoJson = json.optJSONObject("UserInfo");
				if("False".equals(infoJson.optString("IsAnybodyOnBed"))){
					count++;
					if(count == Integer.valueOf(UserInfoManager.getInstance().getLichuangTime())/5){
						//play music
						playSound();
						count = 0;
					}
				}else{
					count = 0;
				}
			}
		}
	}

	private void playSound(){
		if(canPlay){
			pool.play(sourceid, 1, 1, 0, 0, 1);  
		}
	}
	
	@Override
	public void onTaskFailed(SHTask task) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskUpdateProgress(SHTask task, int count, int total) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTaskTry(SHTask task) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (mLeftMenu.isOpen()) {
			mLeftMenu.toggle();
		} else {
			final SweetDialog dia_quit = new SweetDialog(this, SweetDialog.NORMAL_TYPE);
			dia_quit.setTitleText("智照护");
			dia_quit.setContentText("是否退出应用？");
			dia_quit.showCancelButton(true);
			dia_quit.setConfirmText("确认");
			dia_quit.setCancelText("取消");
			dia_quit.setConfirmClickListener(new OnSweetClickListener() {

				@Override
				public void onClick(SweetDialog sweetAlertDialog) {
					sweetAlertDialog.dismiss();
					finish();
					SHApplication.getInstance().exitApplication();
				}
			});
			dia_quit.show();
		}
	}

	// @Override
	// protected void onResume() {
	// // TODO Auto-generated method stub
	// super.onResume();
	// if (SHApplication.getInstance().isLocked) {//判断是否需要跳转到密码界面
	// Intent intent = new Intent(this, SHContainerActivity.class);
	// intent.putExtra("class", SetAppPwdFragment.class.getName());
	// intent.putExtra("isIn", true);
	// startActivity(intent);
	// }
	// }

	private void LoadImage(ImageView img, String path) {
		// 异步加载图片资源
		AsyncTaskImageLoad async = new AsyncTaskImageLoad(img);
		// 执行异步加载，并把图片的路径传送过去
		async.execute(path);

	}
}
